Screen Real Estate

In this recipe we find out what screen resolution the user has on her computer.

Discussion

Under previous versions of JavaScript, you as the script developer were at a loss as to how your scripts (and indeed, your pages composed only of HTML) were going to look on the user's browser. The screen resolution might be 640x480, 800x600, 1024x768, or even 1280x1024. Different screen resolutions affect how the page layout occurs, and you might end up with graphics on top of text, graphics on top of each other, or graphics off the right side of the window (requiring a horizontal scroll bar).

With JavaScript 1.2, you can determine the screen resolution, which will let you write pages that can adapt to different screen sizes, cutting down on layout accidents. The secret is the new screen object, and two of its properties, screen.width and screen.height. The list above was generated with the following combination of HTML and JavaScript 1.2:

<FONT FACE="Arial,Helvectica" SIZE="3">
<UL>
  <LI>Current screen width: <SCRIPT LANGUAGE="JavaScript1.2">document.write(screen.width)</SCRIPT></LI>
  <LI>Current screen height: <SCRIPT LANGUAGE="JavaScript1.2">document.write(screen.height)</SCRIPT></LI>
</UL>
</FONT>

Now you can adapt your pages to the resolution of the user's screen. You might, for example, choose different background graphics. How many times have you seen a tiled background which was supposed to have a scholar's margin down the left hand side of the screen only, but the margin appeared again in the middle of your screen because the background graphic was only 640 pixels wide, and your screen resolution was 800 or 1,024 pixels wide? Your own pages can avoid this kind of mistake by checking the screen resolution and generating a custom <BODY> tag with document.write().

You needn't stop there. You could decide to generate the entire document dynamically based on screen resolution. It's a little more work for you as the developer, but definitely worth the effort from the user's point of view.

For more about this topic, continue on to the Available Screen Real Estate recipe.

Copyright ©2000 by Charles River Media, All Rights Reserved